"""
Case Type   : cm_ctl
Case Name   : 资源池化集群执行cm_ctl pause前,注入网络故障
Create At   : 2024/04/05
Owner       : @kyeleze
Description :
    1.注入网络故障
    2.执行cm_ctl pause
    3.执行cm_ctl resume
Expect      :
    1.成功
    2.失败，合理报错
    3.失败，合理报错
History     :
"""

import os
import unittest
import time

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from yat.test import Node

primary_sh = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != primary_sh.get_node_num(), '非1+2环境不执行')
class CmPauseResumeCase(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.constant = Constant()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.pri_user = Node("PrimaryDbUser")
        self.pri_root = Node("PrimaryRoot")
        self.common = Common()
        self.pause_file = os.path.join('$GAUSSHOME', 'bin/cluster_manual_pause')

    def test_cm(self):
        step = '--step1:注入网络故障 expect:成功--'
        self.log.info(step)
        self.log.info('----获取网卡名称----')
        network_card_cmd = 'ifconfig'
        result = self.common.get_sh_result(self.pri_root, network_card_cmd)
        self.log.info(result)
        network_card_list = result.split('\n\n')
        self.log.info(network_card_list)
        networkcard = ''
        for network_card_item in network_card_list:
            if self.pri_user.db_host in network_card_item:
                networkcard = network_card_item.split(':')[0].strip()
                self.log.info(networkcard)
        self.log.info('----注入网络故障----')
        inject_cmd = f'rNet_down (dev, time)values({networkcard}, 30)'
        result = self.common.cfe_inject(self.pri_root, inject_cmd)
        self.log.info(result)
        self.assertIn(self.constant.cfe_inject_netdown_success_msg,
                      result, "执行失败:" + step)

        step = '--step2:执行cm_ctl pause expect:失败，合理报错--'
        self.log.info(step)
        result = self.primary_sh.exec_cm_ctl('pause')
        self.log.info(result)
        self.assertIn("The ssh trust", result, "执行失败:" + step)

        step = '--step3:执行cm_ctl resume expect:失败，合理报错--'
        self.log.info(step)
        result = self.primary_sh.exec_cm_ctl('resume')
        self.log.info(result)
        self.assertIn("The ssh trust", result, "执行失败:" + step)

    def tearDown(self):
        step = '----恢复环境----'
        self.log.info(step)
        result = self.primary_sh.exec_cm_ctl("resume")
        self.log.info(result)
        self.assertIn(self.constant.cm_resume_success_msg, result,
                      "执行失败:" + step)
        self.log.info(f'----{os.path.basename(__file__)} end----')
